package com.xmim.server;

import com.xmim.core.constants.MessageCode;
import com.xmim.core.entity.Message;
import com.xmim.core.entity.Notification;
import com.xmim.core.exception.ContainerException;
import com.xmim.fulcrum.FulcrumConfig;
import com.xmim.fulcrum.FulcrumDiscover;
import com.xmim.fulcrum.session.FulcrumSessionManager;
import com.xmim.fulcrum.MessageBuilder;
import com.xmim.fulcrum.factory.DefaultFulcrumFactory;
import com.xmim.fulcrum.handler.impl.HeartbeatHandler;
import com.xmim.fulcrum.handler.impl.NotificationHandler;
import com.xmim.fulcrum.handler.impl.RequestHandler;
import com.xmim.server.examples.NettyChannelHandler;
import com.xmim.server.examples.NettyFulcrumSessionManager;
import com.xmim.server.examples.ZKFulcrumDiscover;
import com.xmim.server.serialization.ProtostuffCodec;

import java.util.Scanner;

public class ServerApplication2 {


    /**
     * @param args
     */
    public static void main(String[] args) throws ContainerException {
        FulcrumConfig config = new FulcrumConfig();
        config.setPort(9001);
        config.setZkAddress("122.51.67.236:2181");
        DefaultFulcrumFactory fulcrumFactory = new DefaultFulcrumFactory(config);
        fulcrumFactory.setCodec(new ProtostuffCodec());
        FulcrumDiscover fulcrumDiscover = new ZKFulcrumDiscover(fulcrumFactory, null);
        fulcrumDiscover.setSessionManager(new NettyFulcrumSessionManager(fulcrumDiscover));
        fulcrumDiscover.addHandler(new HeartbeatHandler(fulcrumDiscover));
        fulcrumDiscover.addHandler(new NotificationHandler(fulcrumDiscover));
        fulcrumDiscover.addHandler(new RequestHandler(fulcrumDiscover));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    NettyServer nettyServer = new NettyServer(fulcrumFactory, fulcrumDiscover);
                    nettyServer.addHandler("NettyChannelHandler", new NettyChannelHandler(fulcrumDiscover));
                    nettyServer.start();
                } catch (ContainerException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner input = new Scanner(System.in);
        while (input.hasNext()) {
            String str = input.next();
            System.out.println(str);
            FulcrumSessionManager senderManager = fulcrumDiscover.getSessionManager();
            Message<Notification<String>> stringNotification = MessageBuilder.buildNotificationMsg(MessageCode.NTF_TEST_MSG, str);
            senderManager.writeAllClient(stringNotification);
        }
    }


}
